package org.usmile.algorithms.learn.sort;

import java.util.Arrays;

/**
 * 冒泡排序
 */
public class BubbleSorter {
    public void sort(int[] nums) {
        if (nums == null || nums.length <= 1) {
            return;
        }

        for (int round = nums.length; round >= 1; round--) {
            for (int i = 0; i < round - 1; i++) {
                if (nums[i] > nums[i + 1]) {
                    int temp = nums[i + 1];
                    nums[i + 1] = nums[i];
                    nums[i] = temp;
                }
            }
        }
    }

    // 时间复杂度：O(n^2)
    // 空间复杂度：O(1)
    public void sort1(int[] data) {
        if (data == null || data.length <= 1) return;
        for (int round = 1; round <= data.length; round++) { // 控制冒泡轮数
            boolean hasSwap = false;
            int compareTimes = data.length - round;
            for (int i = 0; i < compareTimes; i++) { // 控制每轮比较次数
                if (data[i] > data[i + 1]) {
                    swap(data, i, i + 1);
                    hasSwap = true;
                }
            }
            if (!hasSwap) break;
        }
    }

    public void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{4, 2, 3, 1};
        new BubbleSorter().sort(nums);
        System.out.println(Arrays.toString(nums));
    }
}
